//
//  HomeViewController.m
//  WeiBTest
//
//  Created by Zc_zhou on 15/9/7.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "HomeViewController.h"
#import "HWDropdownMenu.h"
#import "HWTitleMenuViewController.h"
#import "HWButton.h"
#import "HWUser.h"
#import "HWStatus.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
@interface HomeViewController ()<HWDropdownMenuDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong)UITableView *homeTableView;
@property (nonatomic, strong)NSMutableArray *dateSourceArray;
@property (nonatomic, strong)UILabel *statusNumberLabel;


@end

@implementation HomeViewController
-(NSMutableArray *)dateSourceArray
{
    if (!_dateSourceArray) {
        _dateSourceArray = [[NSMutableArray alloc] init];
        
    }
    return _dateSourceArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setNav];
    [self getUserInformation];
    [self createTableView];
    [self setupReflish];
    
    
}
- (void)createNumberLabel
{
    _statusNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,UiScreen.size.width , 40)];
    _statusNumberLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    _statusNumberLabel.textAlignment = NSTextAlignmentCenter;
    [self.navigationController.view insertSubview:_statusNumberLabel belowSubview:self.navigationController.navigationBar];
    
}
- (void)changeStatusLoaction:(int)count
{
    
    UILabel *label = [[UILabel alloc] init];
    label.width = UiScreen.size.width;
    label.height = 40;
    label.y = 64 - label.height;
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    label.textAlignment = NSTextAlignmentCenter;
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    if (count == 0) {
        label.text = @"没有新微博";
    }
    label.text = [NSString stringWithFormat:@"有%d条新微博",count];
    

    [UIView animateWithDuration:1 animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
        
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
            label.transform = CGAffineTransformIdentity;
            
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
        
    
        
    }];
    
    
}
- (void)setupReflish
{
    
    UIRefreshControl *refControl = [[UIRefreshControl alloc] init];
    [refControl addTarget:self action:@selector(reflishStateChange:) forControlEvents:UIControlEventValueChanged];
    [self.homeTableView addSubview:refControl];
    [self reflishStateChange:refControl];
}
- (void)reflishStateChange:(UIRefreshControl *)control
{
    AFHTTPRequestOperationManager *mg = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    OAuthModel *account= [OAuthTool getOutAccount];
    
    dict[@"access_token"] = account.access_token;
    
    HWStatus *firstStatus = [self.dateSourceArray firstObject];
    
    if (firstStatus) {
        dict[@"since_id"] = firstStatus.idstr;
        
    }
    
    [mg GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            NSArray *arr = [HWStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
            
            NSRange range = NSMakeRange(0, arr.count);
            NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
            [self.dateSourceArray insertObjects:arr atIndexes:set];
            [control endRefreshing];
            [self.homeTableView reloadData];
            [self changeStatusLoaction:arr.count];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [control endRefreshing];
        
    }];
    
}

- (void)reloadData
{
    AFHTTPRequestOperationManager *mg = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    OAuthModel *account= [OAuthTool getOutAccount];
    
    dict[@"access_token"] = account.access_token;
    
    HWStatus *firstStatus = [self.dateSourceArray firstObject];
    
    if (firstStatus) {
        dict[@"since_id"] = firstStatus.idstr;
        
    }
    
    [mg GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            NSArray *arr = [HWStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
            
            NSRange range = NSMakeRange(0, arr.count);
            NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
            [self.dateSourceArray insertObjects:arr atIndexes:set];
            
            [self.homeTableView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
    
}
- (void)createTableView
{
    _homeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UiScreen.size.width, UiScreen.size.height) style:UITableViewStylePlain];
    _homeTableView.delegate = self;
    _homeTableView.dataSource = self;
    [self.view addSubview:_homeTableView];
    
    
}
- (void)getUserInformation
{
    //https://api.weibo.com/2/users/show.json
    OAuthModel *account = [OAuthTool getOutAccount];
    NSMutableDictionary *afDict = [[NSMutableDictionary alloc] init];
    afDict[@"access_token"] = account.access_token;
    afDict[@"uid"] = account.uid;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:afDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            UIButton*titleBtn = (UIButton*)self.navigationItem.titleView;
            [titleBtn setTitle:responseObject[@"name"] forState:UIControlStateNormal];
            account.name =responseObject[@"name"];
            [OAuthTool saveAccount:account];
            
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        HWLog(@"error=%@",error);
    }];
    
}

- (void)setNav
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithimage:@"navigationbar_friendsearch" highImage:@"navigationbar_friendsearch_highlighted" target:self action:@selector(leftClick)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithimage:@"navigationbar_pop" highImage:@"navigationbar_pop_highlighted" target:self action:@selector(leftClick)];
    /* 中间的标题按钮 */
    UIButton *titleButton = [[HWButton alloc] init];
    OAuthModel *accout = [OAuthTool getOutAccount];
    NSString *name = accout.name;
    // 设置图片和文字
    [titleButton setTitle:name?name:@"首页" forState:UIControlStateNormal];
    // 监听标题点击
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleButton;
}
- (void)titleClick:(UIButton *)titleButton
{
   //  1.创建下拉菜单
    HWDropdownMenu *menu = [HWDropdownMenu menu];
    menu.delegate = self;
    // 2.设置内容
    HWTitleMenuViewController *vc = [[HWTitleMenuViewController alloc] init];
    vc.view.height = 150;
    vc.view.width = 150;
    menu.contentController = vc;
    
    // 3.显示
    [menu showFrom:titleButton];

}
#pragma mark- HWDropdownMenu代理协议
-(void)showTheTitleImage:(HWDropdownMenu *)menu
{
    UIButton *btn = (UIButton *)self.navigationItem.titleView;
    btn.selected = YES;
}
-(void)hideTheTitleImage:(HWDropdownMenu *)menu
{
    UIButton *btn = (UIButton *)self.navigationItem.titleView;
    btn.selected = NO;
}
- (void)leftClick
{
    NSLog(@"friendSearch");
}
- (void)right
{
    NSLog(@"right");
}

#pragma mark- UITableView代理协议
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dateSourceArray.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"cellId";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    HWStatus *status = self.dateSourceArray[indexPath.row];
    
    cell.textLabel.text = status.user.name;
    cell.detailTextLabel.text = status.text;
    
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:status.user.profile_image_url] placeholderImage:[UIImage imageNamed:@"avatar_default_small"]];
    
    
    return cell;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
